#include "file_io.h"
#include "dbg.h"

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

unsigned long get_file_size(const char *file_name)
{
    struct stat buf;
    if (stat(file_name, &buf) == -1)
        return 0;
    
    return buf.st_size;
}

int file_io_getfile_size(int fd)
{
	struct stat st;
	if (fd < 0) return -1;

	// 检查文件长度是否正确
	if (fstat(fd, &st) < 0)
	{
		return -2;
	}
	return (int)st.st_size;
}

int file_io_cp(char *src, char *dst)
{
  	int ret;	      
    char argv[256] = {0x00};
	sprintf(argv, "/bin/cp %s %s", src, dst);	
	ret = system(argv);
	return ret;
}

int file_io_mv(char *src,char *dst)
{
  	int ret;	
	char argv[256] = {0x00};
	sprintf(argv, "/bin/mv %s %s", src, dst);	
	ret = system(argv);
	return ret;
}

int file_io_del(char *pathname)
{
  	int ret;	
	char argv[256] = {0x00};
	sprintf(argv, "/bin/rm -f %s", pathname);	
	ret = system(argv);
	return ret;
}

int file_io_mkdir(char *dir)
{
  	int ret;
	char argv[256] = {0x00};
	if(opendir(dir) != NULL)
		return 1;

	sprintf(argv, "/bin/mkdir %s", dir);	
	ret = system(argv);
	return ret;
}

int file_io_ln(char *src, char *dst)
{
  	int ret;
	char argv[256] = {0x00};
	sprintf(argv, "/bin/ln -s %s %s", src, dst);	
	ret = system(argv);
	return ret;
}

int file_io_read_seek(const char *_fileName, char *buffer, uint16_t len, uint16_t index)
{
    int ret = 0;
    FILE *fp = fopen(_fileName, "rb");
    if (NULL == fp) 
    {
        dbg_err("Open file failed: %s", _fileName);
        return -2;
    }
    
	unsigned long fileSize = get_file_size(_fileName);
	if ((index * (len - 1)) > fileSize)
	{
		dbg_err("文件已加载完成!~");
		fclose(fp);
		return -1;	
	}
   
	fseek(fp, index * len, SEEK_SET);
    if (feof(fp) == 0)
    {
        memset(buffer, 0x00, len);
        fread(buffer, len, 1, fp);
        dbg_msg("send packet index: %d", index);
    }
    else {
       ret = -1;
    }

    fclose(fp);
    return ret;
}